﻿using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using clf.weighing.entity;
using TextBox = System.Windows.Controls.TextBox;
using Brushes = System.Windows.Media.Brushes;

namespace weighing
{
    /// <summary>
    /// BuLuWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BuLuWindow : GlowWindow
    {
        #region  variables      
        private WeighingBill mWeighingBill;
        protected CompanyVo sendCompanyVo;
        protected CompanyVo receiverCompanyVo;
        protected CompanyVo tranceCompanyVo;
        protected MaterialVo currMaterialVo;
        protected CarInfoVo currCarVo;
        private bool isSaving = false;


        protected CompanyVo lockSendCompanyVo;
        protected CompanyVo lockReceiverCompanyVo;
        protected MaterialVo lockMaterialVo;

        protected ObservableCollection<YardVo> ShareYrardVos = new ObservableCollection<YardVo>();
        protected ObservableCollection<YardVo> SendCompanyYrardVos = new ObservableCollection<YardVo>();
        protected ObservableCollection<YardVo> ReceiveCompanyYrardVos = new ObservableCollection<YardVo>();
        #endregion

        public BuLuWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }

        #region  window event

        private void Bu_Lu_Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.inFactoryRb.IsChecked = true;

            SetDefaultSource();

            //动态插入备用字段，并保存补录的值
            CreateBackFillUI();
        }

        private void Bu_Lu_Window_ContentRendered(object sender, EventArgs e)
        {
            this.userTb.Text = App.CurrentUser.name;
            SetWeihinger();

            this.inputPanel.DataContext = App.Config.WeighingConfig;

            if(mWeighingBill.type == (int)WeightingBillType.Buy)
            {
                CommonFunction.SetRemarkItemSource(this.remarkCb,true);
                CommonFunction.SetDecuationItemSource(this.decuDescCb);
            }
            else
            {
                CommonFunction.SetRemarkItemSource(this.remarkCb, false);
            }   
        }


        #endregion

        /// <summary>
        ///TODO 扑录创建 备用字段的UI
        /// </summary>
        private void CreateBackFillUI()
        {
            int type = inFactoryRb.IsChecked == true ? (int)WeightingBillType.Buy : outFactoryRb.IsChecked == true ? (int)WeightingBillType.Sale : 0;
            List<BackupBillField> backupBills = BackupBillFieldDao.Instance.SelectAllByType(type);
            if (backupBills == null || backupBills.Count == 0)
            {
                this.backFieldPanel.Children.Clear();
            }
            else
            {
                this.backFieldPanel.Children.Clear();
                for (int i = 0; i < backupBills.Count; i++)
                {

                    var item = backupBills[i];
                    int w = item.width < 200 ? 200 : item.width;
                    w = item.width > 400 ? 400 : item.width;
                    if (item.isEnable == 1)
                    {
                        TextBox textBox = new TextBox()
                        {
                            Name = item.fiedName + "TB",
                            Style = FindResource("TextBoxExtend") as Style,
                            Margin = new Thickness(10, 2, 10, 2),
                            MinWidth = 100,
                            MaxWidth = 400,
                            Width = w,
                            FontSize = 14
                        };
                        InfoElement.SetTitle(textBox, item.displayName);
                        InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
                        InfoElement.SetTitleWidth(textBox, new GridLength(Convert.ToDouble(item.titleWidth)));

                        this.backFieldPanel.Children.Add(textBox);
                    }
                }
            }
        }

        /// <summary>
        /// 获取备用字段的值
        /// </summary>
        private bool GetBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var tb = this.backFieldPanel.Children[i] as TextBox;
                    if (tb != null)
                    {
                        var name = tb.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            mWeighingBill.backupString1 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            mWeighingBill.backupString2 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            mWeighingBill.backupString3 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            mWeighingBill.backupString4 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            mWeighingBill.backupString5 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {

                            mWeighingBill.backupInt1 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {

                            mWeighingBill.backupInt2 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {

                            mWeighingBill.backupInt3 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {

                            mWeighingBill.backupInt4 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            mWeighingBill.backupInt5 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            mWeighingBill.backupDecimal1 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            mWeighingBill.backupDecimal2 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            mWeighingBill.backupDecimal3 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            mWeighingBill.backupDecimal4 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            mWeighingBill.backupDecimal5 = Convert.ToDecimal(tb.Text.Trim());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message);
                    return false;
                }

            }
            return true;
        }

        //入库
        private void InFactoryRb_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded == false)
            {
                return;
            }
            mWeighingBill = new WeighingBill()
            {
                type = (int)WeightingBillType.Buy,
            };
            string number = BillNumberHelper.GetWeighingNumber(WeightingBillType.Buy, "BL");
            this.inputPanel.Background = Brushes.LemonChiffon;
            billnumberTb.Text = number;
            mWeighingBill.number = number;
            this.sendNetWeightTb.Visibility = Visibility.Visible;
            this.diffWeightTb.Visibility = Visibility.Visible;
            this.decuDescCb.Visibility = Visibility.Visible;
            this.decuationWeightTb.Visibility = Visibility.Visible;
            if (lockSendCompanyVo == null)
            {
                this.sendCompanyCb.SelectedIndex = -1;
                this.sendCompanyCb.IsEnabled = true;
                this.sendCompanyCb.Text = "";
            }
            if (App.Config.WeighingConfig.InNecessarySendWeighing)
            {
                this.sendNetWeightTb.Visibility = Visibility.Visible;
            }
            else
            {
                this.sendNetWeightTb.Visibility = Visibility.Collapsed;
            }
            this.TranceCompanyCb.Visibility = App.Config.WeighingConfig.InNecessaryTranceCompany ? Visibility.Visible : Visibility.Collapsed;
            if (lockReceiverCompanyVo == null)
            {
                this.RecevieCompanyCb.SelectedIndex = -1;
                this.RecevieCompanyCb.IsEnabled = true;
                this.RecevieCompanyCb.Text = "";
            }
        }
        //出库
        private void OutFactoryRb_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded == false)
            {
                return;
            }
            mWeighingBill = new WeighingBill()
            {
                type = (int)WeightingBillType.Sale,
            };
            this.inputPanel.Background = Brushes.LightSalmon;
            string number = BillNumberHelper.GetWeighingNumber(WeightingBillType.Sale, "BL");
            billnumberTb.Text = number;
            mWeighingBill.number = number;
            this.sendNetWeightTb.Visibility = Visibility.Collapsed;
            this.diffWeightTb.Visibility = Visibility.Collapsed;
            this.decuDescCb.Visibility = Visibility.Collapsed;
            this.decuationWeightTb.Visibility = Visibility.Collapsed;
            if (lockReceiverCompanyVo == null)
            {
                this.RecevieCompanyCb.SelectedIndex = -1;
                this.RecevieCompanyCb.IsEnabled = true;
                this.RecevieCompanyCb.Text = "";
            }

            this.TranceCompanyCb.Visibility = App.Config.WeighingConfig.OutNecessaryTranceCompany ? Visibility.Visible : Visibility.Collapsed;
            if (lockSendCompanyVo == null)
            {
                this.sendCompanyCb.SelectedIndex = -1;
                this.sendCompanyCb.IsEnabled = true;
                this.sendCompanyCb.Text = "";
            }
        }


        private void SelfRb_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded == false)
            {
                return;
            }
            mWeighingBill = new WeighingBill()
            {
                type = (int)WeightingBillType.Self,
            };
            this.inputPanel.Background = Brushes.LightGray;
            string number = BillNumberHelper.GetWeighingNumber(WeightingBillType.Self, "BL");
            billnumberTb.Text = number;
            mWeighingBill.number = number;
            this.sendNetWeightTb.Visibility = Visibility.Collapsed;
            this.diffWeightTb.Visibility = Visibility.Collapsed;
            this.decuDescCb.Visibility = Visibility.Collapsed;
            this.decuationWeightTb.Visibility = Visibility.Collapsed;
            if (lockReceiverCompanyVo == null)
            {
                this.RecevieCompanyCb.SelectedIndex = -1;
                this.RecevieCompanyCb.IsEnabled = true;
                this.RecevieCompanyCb.Text = "";
            }

            this.TranceCompanyCb.Visibility = App.Config.WeighingConfig.OutNecessaryTranceCompany ? Visibility.Visible : Visibility.Collapsed;

            if (lockSendCompanyVo == null)
            {
                this.sendCompanyCb.SelectedIndex = -1;
                this.sendCompanyCb.IsEnabled = true;
                this.sendCompanyCb.Text = "";
            }

        }

        //保存
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!App.Config.SystemConfig.Debug && App.CurrentUser.roleType == (int)UserRoleType.Developer)
            {
                Growl.Info("非调试模式下，你无权操作", "bulu");
                return;
            }
            if (isSaving)
            {
                return;
            }
            isSaving = true;

            if (CheckInput() == false)
            {
                isSaving = false;
                return;
            }
            //设置备用字段值时产生了错误 An error occurred while setting the fallback field value
            if (GetBackFieldValue() == false)
            {
                isSaving = false;
                return;
            }

            mWeighingBill.id = IdHelper.LongID;
            mWeighingBill.status = 1;
            mWeighingBill.addTime = DateTime.Now;
            mWeighingBill.addUserId = App.CurrentUser?.id??0;
            mWeighingBill.addUserName = App.CurrentUser?.name??"";
            mWeighingBill.syncTime = DateTimeHelper.GetTimeStamp();
            mWeighingBill.remark = this.remarkCb.Text;
            mWeighingBill.affiliatedCompanyId = App.CurrentCompanyVo?.Id??0;
            mWeighingBill.printTimes = 0;
            mWeighingBill.sendNetWeight = mWeighingBill.netWeight;
            mWeighingBill.isDelete = 0;
            mWeighingBill.moneyType = (int)MoneyType.Cash;
            mWeighingBill.unitText = App.UnitText;
            SetWeihinger();

            if (App.Config.SystemConfig.Debug)
            {
                mWeighingBill.dataType = (int)DataType.Debug;
            }
            else
            {
                mWeighingBill.dataType = (int)DataType.Prod;
            }

            if (this.inFactoryRb.IsChecked == true)
            {
                var sw = this.sendNetWeightTb.Text;
                if (string.IsNullOrEmpty(sw)) sw = "0";
                mWeighingBill.sendNetWeight = Convert.ToDecimal(this.sendNetWeightTb.Text.Trim());
                if (this.decuDescCb.Text.Trim().Length > 0)
                {
                    mWeighingBill.decuationDescription = this.decuDescCb.Text.Trim();
                }
            }

            int res = WeighingBillDao.Instance.Insert(mWeighingBill);
            if (res > 0)
            {
                Growl.Success("保存成功", "bulu");
                //print
                new PrintWindow(mWeighingBill?.id ?? 0,WeightingBillType.WeighintBill) { 
                    Owner = this 
                }.ShowDialog();

                var msg = "保存成功,是否要关闭窗口";
                var result = CommonFunction.Ask(msg);
                if (result == MessageBoxResult.Yes)
                {
                    this.Close();
                }
                else
                {
                    //重置输入框
                    ResertInput();
                }
            }
            else
            {
                Growl.Error("保存失败", "bulu");
            }
            isSaving = false;
        }

        //验证输入
        private bool CheckInput()
        {

            if (mWeighingBill.type == (int)WeightingBillType.Sale && App.Config.WeighingConfig.OutNecessarySend)
            {
                if (mWeighingBill.sendCompanyId == null && lockSendCompanyVo != null)
                {
                    mWeighingBill.sendCompanyId = lockSendCompanyVo.Id;
                }
                if (mWeighingBill.sendCompanyName.IsNullOrEmpty() && lockSendCompanyVo != null)
                {
                    mWeighingBill.sendCompanyName = lockSendCompanyVo.FullName;
                }

                if (mWeighingBill.sendCompanyId == null || mWeighingBill.sendCompanyId <= 0 || mWeighingBill.sendCompanyName.IsNullOrEmpty())
                {
                    Growl.Error("请选择发货公司信息", "bulu");
                    this.sendCompanyCb.Focus();
                    return false;
                }
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Sale && App.Config.WeighingConfig.OutNecessarySend)
            {
                if (mWeighingBill.sendCompanyId == null && lockSendCompanyVo != null)
                {
                    mWeighingBill.sendCompanyId = lockSendCompanyVo.Id;
                }
                if (mWeighingBill.sendCompanyName.IsNullOrEmpty() && lockSendCompanyVo != null)
                {
                    mWeighingBill.sendCompanyName = lockSendCompanyVo.FullName;
                }

                if (mWeighingBill.sendCompanyId == null || mWeighingBill.sendCompanyId <= 0 || mWeighingBill.sendCompanyName.IsNullOrEmpty())
                {
                    Growl.Error("请选择发货公司信息", "bulu");
                    this.sendCompanyCb.Focus();
                    return false;
                }
            }
            else
            {
                mWeighingBill.sendCompanyId = 0;
                mWeighingBill.sendCompanyName = this.sendCompanyCb.Text;
            }
            var necessarySendYard = this.inFactoryRb.IsChecked == true ? App.Config.WeighingConfig.InNecessarySendYard
            : App.Config.WeighingConfig.OutNecessarySendYard;



            if ((mWeighingBill.type == (int)WeightingBillType.Buy && App.Config.WeighingConfig.InNecessaryReceive))
            {
                if (mWeighingBill.receiveCompanyId == null && lockReceiverCompanyVo != null)
                {
                    mWeighingBill.receiveCompanyId = lockReceiverCompanyVo.Id;
                }
                if (mWeighingBill.receiveCompanyName.IsNullOrEmpty() && lockReceiverCompanyVo != null)
                {
                    mWeighingBill.receiveCompanyName = lockReceiverCompanyVo.FullName;
                }

                if (mWeighingBill.receiveCompanyId == null || mWeighingBill.receiveCompanyId <= 0 || string.IsNullOrEmpty(mWeighingBill.receiveCompanyName))
                {
                    Growl.Error("请选择收货公司", "bulu");
                    this.RecevieCompanyCb.Focus();
                    return false;
                }
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Sale && App.Config.WeighingConfig.OutNecessaryReceive)
            {
                if (mWeighingBill.receiveCompanyId == null && lockReceiverCompanyVo != null)
                {
                    mWeighingBill.receiveCompanyId = lockReceiverCompanyVo.Id;
                }
                if (mWeighingBill.receiveCompanyName.IsNullOrEmpty() && lockReceiverCompanyVo != null)
                {
                    mWeighingBill.receiveCompanyName = lockReceiverCompanyVo.FullName;
                }

                if (mWeighingBill.receiveCompanyId == null || mWeighingBill.receiveCompanyId <= 0 || string.IsNullOrEmpty(mWeighingBill.receiveCompanyName))
                {
                    Growl.Error("请选择收货公司", "bulu");
                    this.RecevieCompanyCb.Focus();
                    return false;
                }
            }
            else
            {
                mWeighingBill.receiveCompanyId = 0;
                mWeighingBill.receiveCompanyName = this.RecevieCompanyCb.Text;
            }
            var necessaryReceiveYard = this.inFactoryRb.IsChecked == true ? App.Config.WeighingConfig.InNecessaryReceiveYard
               : App.Config.WeighingConfig.OutNecessaryReceiveYard;

            var necessaryTrance = this.inFactoryRb.IsChecked == true ? App.Config.WeighingConfig.InNecessaryTranceCompany
                : App.Config.WeighingConfig.OutNecessaryTranceCompany;
            //运输公司
            if (necessaryTrance)
            {
                if (mWeighingBill.tranceCompanyId == 0 || string.IsNullOrEmpty(mWeighingBill.tranceCompanyName))
                {
                    this.TranceCompanyCb.Text = string.Empty;
                    this.TranceCompanyCb.Focus();
                    string msg = "请选运输公司";
                    Growl.Warning(msg, "main");
                    return false;
                }
            }


            if (InfoElement.GetNecessary(this.materialCb) == true)
            {
                if (mWeighingBill.materialId == null && lockMaterialVo != null)
                {
                    mWeighingBill.materialId = lockMaterialVo.Id;
                }
                if (mWeighingBill.materialName.IsNullOrEmpty() && lockMaterialVo != null)
                {
                    mWeighingBill.materialName = lockMaterialVo.Name;
                }

                if (mWeighingBill.materialId == null || mWeighingBill.materialId <= 0 || string.IsNullOrEmpty(mWeighingBill.materialName))
                {
                    Growl.Error("请选择物资名称", "bulu");
                    this.materialCb.Focus();
                    return false;
                }
            }
            else
            {
                mWeighingBill.materialId = 0;
                mWeighingBill.materialName = this.materialCb.Text;
            }
            if (mWeighingBill.carId == null || mWeighingBill.carId <= 0 || string.IsNullOrEmpty(mWeighingBill.carNumber))
            {
                if (RegexHelper.IsVehicleNumber(this.carNumberCb.Text))
                {
                    var car = new CarInfo()
                    {
                        id = IdHelper.LongID,
                        carNumber = this.carNumberCb.Text,
                        addTime = DateTime.Now,
                        addUserId = App.CurrentUser.id,
                        addUserName = App.CurrentUser.name,
                        remark = "自动添加",
                        traeWeight = 0,
                        driver = this.driverTb.Text,
                        driverMobile = this.phoneTb.Text
                    };
                    currCarVo = new CarInfoVo(car);
                    mWeighingBill.carId = currCarVo.Id;
                    mWeighingBill.carNumber = currCarVo.CarNumber;
                    mWeighingBill.driver = currCarVo.Driver;
                    mWeighingBill.driverMobile = currCarVo.DriverMobile;
                }
                else
                {
                    if (mWeighingBill.type == (int)WeightingBillType.Buy)
                    {
                        if (App.Config.WeighingConfig.InCheckCarNumber)
                        {
                            CommonFunction.AlertInfo("请输入车辆信息");
                            this.carNumberCb.Focus();
                            return false;
                        }
                        else
                        {
                            mWeighingBill.carId = 0;
                            mWeighingBill.carNumber = this.carNumberCb.Text;
                            mWeighingBill.driver = this.driverTb.Text;
                            mWeighingBill.driverMobile = this.phoneTb.Text;
                        }
                    }
                    else if (mWeighingBill.type == (int)WeightingBillType.Sale)
                    {
                        if (App.Config.WeighingConfig.OutCheckCarNumber)
                        {
                            CommonFunction.AlertInfo("请输入车辆信息");
                            this.carNumberCb.Focus();
                            return false;
                        }
                        else
                        {
                            mWeighingBill.carId = 0;
                            mWeighingBill.carNumber = this.carNumberCb.Text;
                            mWeighingBill.driver = this.driverTb.Text;
                            mWeighingBill.driverMobile = this.phoneTb.Text;
                        }
                    }
                }
            }

            //入场时间 
            if (this.startDateTime.SelectedDateTime == null)
            {
                Growl.Error("请选择入场时间", "bulu");
                return false;
            }
            if (this.startDateTime.SelectedDateTime >= DateTime.Now)
            {
                Growl.Error("入场时间错误", "bulu");
                return false;
            }
            mWeighingBill.inTime = this.startDateTime.SelectedDateTime;
            //出场时间
            if (this.endDateTime.SelectedDateTime == null)
            {
                Growl.Error("请选择出场时间", "bulu");
                return false;
            }
            if (this.endDateTime.SelectedDateTime > DateTime.Now)
            {
                Growl.Error("出场时间错误，不能大于当前时间。", "bulu");
                return false;
            }
            mWeighingBill.outTime = this.endDateTime.SelectedDateTime;
            if (mWeighingBill.inTime > mWeighingBill.outTime)
            {
                Growl.Error("入场或者出场的时间选择错误 !", "bulu");
                mWeighingBill.outTime = null;
                return false;
            }
            if (mWeighingBill.outTime == null)
            {
                Growl.Error("出场的时间选择错误 !", "bulu");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 重置输入框
        /// </summary>
        private void ResertInput()
        {
            WeightingBillType type = WeightingBillType.UNKNOWN;
            if (selfRb.IsChecked == true)
            {
                type = WeightingBillType.Self;
            }
            else if (inFactoryRb.IsChecked == true)
            {
                type = WeightingBillType.Buy;
            }
            else if (outFactoryRb.IsChecked == true)
            {
                type = WeightingBillType.Sale;
            }

            mWeighingBill = new WeighingBill()
            {
                id = IdHelper.LongID,
                type = (int)type,
            };

            this.carNumberCb.SelectedIndex = -1;

            if (lockSendCompanyVo == null) this.sendCompanyCb.SelectedIndex = -1;
            if (lockReceiverCompanyVo == null) this.RecevieCompanyCb.SelectedIndex = -1;
            if (lockMaterialVo == null) this.materialCb.SelectedIndex = -1;

            this.sendCompanyVo = null;
            this.receiverCompanyVo = null;
            this.currMaterialVo = null;
            this.currCarVo = null;
            this.driverTb.Text = string.Empty;
            this.phoneTb.Text = string.Empty;
            this.sendNetWeightTb.Text = "0";
            this.grossWeightTb.Text = "0";
            this.TraeWeightTb.Text = "0";
            this.netWeightTb.Text = "0";

            this.tranceCompanyVo = null;
            this.TranceCompanyCb.SelectedIndex = -1;
            this.remarkCb.SelectedIndex = -1;
            this.decuationWeightTb.Text = "0";
            this.decuDescCb.SelectedIndex = -1;

            this.startDateTime.SelectedDateTime = null;
            this.endDateTime.SelectedDateTime = null;

            if (type == WeightingBillType.UNKNOWN)
            {
                this.inFactoryRb.IsChecked = true;
            }
            string number = BillNumberHelper.GetWeighingNumber(type, "BL");
            mWeighingBill.number = number;
            this.billnumberTb.Text = number;
        }

        #region 输入改变事件
        private void GrossWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }

        private void TraeWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        //扣吨
        private void DecuationWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        //原发净重
        private void SendNetWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        /// <summary>
        /// 计算吨位  calculating the tonnage of receipt
        /// </summary>
        private void CalcToneValue()
        {
            if (this.IsLoaded == false) return;

            decimal gross = 0, trace = 0, net, sendNet = 0, decu = 0, diff;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { trace = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }
            mWeighingBill.grossWeight = gross;
            mWeighingBill.traeWeight = trace;
            if (inFactoryRb.IsChecked == true)
            {
                try { sendNet = Convert.ToDecimal(this.sendNetWeightTb.Text); } catch { }
                try { decu = Convert.ToDecimal(this.decuationWeightTb.Text); } catch { }
                net = Math.Round(gross - trace - decu, 2); ;
                diff = Math.Round(net - sendNet, 2);
                mWeighingBill.netWeight = net;
                mWeighingBill.sendNetWeight = sendNet;
                mWeighingBill.diffWeight = diff;
                mWeighingBill.decuationWeight = decu;
                this.diffWeightTb.Text = diff.ToString();
                this.netWeightTb.Text = net.ToString();
            }
            else
            {
                net = Math.Round(gross - trace, 2);
                mWeighingBill.netWeight = net;
                mWeighingBill.diffWeight = 0;
                this.netWeightTb.Text = net.ToString();
            }
        }
        #endregion

        #region Supply 
        private bool isSupplySelected = false;
        private void SupplyCb_TextChanged(object sender, TextChangedEventArgs e)
        {

            String text = this.sendCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                isSupplySelected = false;
                this.sendCompanyCb.IsDropDownOpen = false;
            }
            if (isSupplySelected == true)
            {
                return;
            }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count <= 0)
                {
                    isSupplySelected = false;
                }
                sendCompanyCb.ItemsSource = list.Select((i) => { return new CompanyVo(i); });
                if (sendCompanyCb.ItemsSource != null)
                {
                    this.sendCompanyCb.IsDropDownOpen = true;
                }
            }

        }
        private void SupplyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sendCompanyCb.SelectedIndex == -1)
            {
                this.sendCompanyCb.Text = "";
                sendCompanyVo = null;
                return;
            }
            isSupplySelected = true;
            sendCompanyVo = sendCompanyCb.SelectedItem as CompanyVo;
            if (sendCompanyVo != null)
            {
                if (CheckSupplyCustomer() == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    this.sendCompanyCb.Text = "";
                    sendCompanyVo = null;
                }
                else
                {
                    mWeighingBill.sendCompanyId = sendCompanyVo.Id;
                    mWeighingBill.sendCompanyName = sendCompanyVo.FullName;
                }

            }
        }



        #endregion

        #region Receiver Company
        private bool isSelectReceiveCompany = false;
        private void ReceiverCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {

            String text = this.RecevieCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                isSelectReceiveCompany = false;
                this.RecevieCompanyCb.IsDropDownOpen = false;
            }
            if (isSelectReceiveCompany == true) { return; }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count > 0)
                {
                    isSelectReceiveCompany = true;
                }
                this.RecevieCompanyCb.ItemsSource = list.Select((i) => { return new CompanyVo(i); });
                if (this.RecevieCompanyCb.ItemsSource != null)
                {
                    this.RecevieCompanyCb.IsDropDownOpen = true;
                }
                else
                {
                    this.RecevieCompanyCb.IsDropDownOpen = false;
                }
            }
        }
        private void ReceiverCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecevieCompanyCb.SelectedIndex == -1)
            {
                RecevieCompanyCb.Text = "";
                receiverCompanyVo = null;
                return;
            };
            isSelectReceiveCompany = true;
            receiverCompanyVo = RecevieCompanyCb.SelectedItem as CompanyVo;
            if (receiverCompanyVo != null)
            {
                if (CheckSupplyCustomer() == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    RecevieCompanyCb.Text = "";
                    receiverCompanyVo = null;
                }
                else
                {
                    mWeighingBill.receiveCompanyId = receiverCompanyVo.Id;
                    mWeighingBill.receiveCompanyName = receiverCompanyVo.FullName;
                }

            }
        }
        /// <summary>
        /// 供应商和客户是不能是同一个公司
        /// </summary>
        /// <returns></returns>
        private bool CheckSupplyCustomer()
        {
            if (receiverCompanyVo != null && sendCompanyVo != null)
            {
                if (receiverCompanyVo.Id == sendCompanyVo.Id)
                {
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region Material 
        private bool isSelectMaterial = false;
        private void MaterialNameCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            String text = this.materialCb.Text.Trim();
            if (text.Length < 2)
            {
                isSelectMaterial = false;
                this.materialCb.IsDropDownOpen = false;
            }
            if (isSelectMaterial == true) { return; }
            if (text.Length >= 2)
            {
                List<Material> list = MaterialDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count > 0)
                {
                    isSelectMaterial = true;
                }

                this.materialCb.ItemsSource = list.Select((i) => { return new MaterialVo(i); });
                if (this.materialCb.ItemsSource != null)
                {
                    this.materialCb.IsDropDownOpen = true;
                }
                else
                {
                    this.materialCb.IsDropDownOpen = false;
                }
            }
        }

        private void MaterialNameCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (materialCb.SelectedIndex != -1)
            {
                isSelectMaterial = true;
                currMaterialVo = (MaterialVo)materialCb.SelectedItem;
                mWeighingBill.materialId = currMaterialVo.Id;
                mWeighingBill.materialName = currMaterialVo.Name;
            }
        }
        #endregion

        #region CarInfo Selection
        private bool isCarInfoSelectioned = false;
        private void CarNumberCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            String text = this.carNumberCb.Text.Trim();
            if (text.Length <= 0)
            {
                isCarInfoSelectioned = false;
                currCarVo = null;
                this.carNumberCb.IsDropDownOpen = false;
                SetCarInfo();
                return;
            }
            if (isCarInfoSelectioned == true) { return; }

            if (text.Length >= 2)
            {
                List<CarInfo> list = CarDao.Instance.SelectByLike(text);
                if (list.Count > 0)
                {
                    isCarInfoSelectioned = true;
                }
                this.carNumberCb.ItemsSource = list.Select((i) => { return new CarInfoVo(i); });
                if (carNumberCb.ItemsSource != null)
                {
                    this.carNumberCb.IsDropDownOpen = true;
                }
            }
        }

        private void CarNumberCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (carNumberCb.SelectedIndex >= 0)
            {
                currCarVo = (CarInfoVo)carNumberCb.SelectedItem;
                isCarInfoSelectioned = true;
                mWeighingBill.carNumber = currCarVo.CarNumber;
                mWeighingBill.carId = currCarVo.Id;
                mWeighingBill.driver = currCarVo.Driver;
                //mWeighingBill.driverIdNumber = currCarVo.driverIdnumber;
                mWeighingBill.driverMobile = currCarVo.DriverMobile;

                SetCarInfo();
            }
            else
            {
                this.currCarVo = null;
                SetCarInfo();
            }
        }

        private void SetCarInfo()
        {
            if (currCarVo != null)
            {
                this.driverTb.Text = currCarVo.Driver;
                this.phoneTb.Text = currCarVo.DriverMobile;
            }
            else
            {
                this.driverTb.Text = string.Empty;
                this.driverTb.Text = string.Empty;
            }
        }
        #endregion

        #region Weihinger
        private void SetWeihinger()
        {
            if (mWeighingBill == null) return;
            this.userTb.Text = App.CurrentUser.name;
            mWeighingBill.userId = App.CurrentUser.id;
            mWeighingBill.outUserName = App.CurrentUser.name;
            mWeighingBill.inUserName = App.CurrentUser.name;
            this.userTb.Text = App.CurrentUser.name;
        }
        #endregion



        #region 运输公司

        private bool isSelectTranceCompany = false;

        private void TranceCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            String text = this.TranceCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                tranceCompanyVo = null;
                isSelectTranceCompany = false;
                this.TranceCompanyCb.IsDropDownOpen = false;
            }
            if (isSelectTranceCompany == true) { return; }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                var data = list?.Select((i) => { return new CompanyVo(i); }).ToList();
                this.TranceCompanyCb.ItemsSource = data;
                isSelectTranceCompany = list?.Count > 0;
                if (this.TranceCompanyCb.ItemsSource != null)
                {
                    this.TranceCompanyCb.IsDropDownOpen = true;
                }
                else
                {
                    this.TranceCompanyCb.IsDropDownOpen = false;
                }
            }

        }

        private void TranceCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            isSelectTranceCompany = this.TranceCompanyCb.SelectedIndex > -1;
            tranceCompanyVo = TranceCompanyCb.SelectedItem as CompanyVo;
            if (mWeighingBill != null)
            {
                mWeighingBill.tranceCompanyId = tranceCompanyVo.Id;
                mWeighingBill.tranceCompanyName = tranceCompanyVo.FullName;
            }
        }
        #endregion



        #region 将本机使用的基础数据设置默认数据源 最新使用的排在最前面
        /// <summary>
        /// 将本机使用的基础数据设置默认数据源 
        /// </summary>
        private void SetDefaultSource()
        {
            this.sendCompanyCb.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
            this.RecevieCompanyCb.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
            this.TranceCompanyCb.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
            this.materialCb.ItemsSource = RuntimeData.Instance.TempMaterial.ToList();
            this.carNumberCb.ItemsSource = RuntimeData.Instance.TempCars.ToList();

            if (this.inFactoryRb.IsChecked == true)
            {
                CommonFunction.SetRemarkItemSource(this.remarkCb, true);
                CommonFunction.SetDecuationItemSource(this.decuDescCb);
            }
            else
            {
                CommonFunction.SetRemarkItemSource(this.remarkCb, false);
            }
            //CommonFunction.SetRemarkItemSource(this.remarkCb, this.inFactoryRb.IsChecked== true);
            //this.decuDescCb.ItemsSource = App.decuationDesList;
        }

        #endregion


        #region 车牌号输入

        private void KeyBoardBtn_Click(object sender, RoutedEventArgs e)
        {
            this.carInputPopup.IsOpen = !this.carInputPopup.IsOpen;
            if (this.carInputPopup.IsOpen)
            {
                this.carNumberInput.Complated += On_Complated;
            }
            else
            {
                this.carNumberInput.Complated -= On_Complated;
            }
        }

        private void On_Complated(string res)
        {
            this.carNumberCb.Text = res;
            this.carInputPopup.IsOpen = false;
        }
        #endregion



        #region lock weighing 锁定过磅
        private static readonly string lockGeomitryName = "LockFill";
        private static readonly string unLockGeomitryName = "UnLock";
        private Geometry lockG = App.Current.FindResource(lockGeomitryName) as Geometry;
        private Geometry unlockG = App.Current.FindResource(unLockGeomitryName) as Geometry;

        #region lock 发货公司
        private void LockSendBtn_Click(object sender, RoutedEventArgs e)
        {
            var combomBox = this.sendCompanyCb;
            string title = InfoElement.GetTitle(combomBox);
            var btn = this.lockSendBtn;
            string msg;
            if (lockSendCompanyVo != null)
            {
                //点击解锁
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(btn, unlockG);
                btn.Foreground = Brushes.Gray;
                this.lockSendCompanyVo = null;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
                combomBox.IsEnabled = true;
            }
            else
            {
                var vo = combomBox.SelectedItem as CompanyVo;
                if (vo == null)
                {
                    msg = "请选择，再点击锁定";
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                lockSendCompanyVo = vo;
                //点击锁定
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(btn, lockG);
                btn.Foreground = Brushes.PaleVioletRed;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = new List<CompanyVo>() { lockSendCompanyVo };
                combomBox.IsEnabled = false;
                combomBox.SelectedIndex = 0;
            }
        }

        #endregion

        #region lock 收货公司

        private void LockReceiveBtn_Click(object sender, RoutedEventArgs e)
        {
            var combomBox = this.RecevieCompanyCb;
            string title = InfoElement.GetTitle(combomBox);
            var btn = this.lockReceiveBtn;
            string msg;
            if (lockReceiverCompanyVo != null)
            {
                //点击解锁
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(btn, unlockG);
                btn.Foreground = Brushes.Gray;
                this.lockSendCompanyVo = null;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
                combomBox.IsEnabled = true;
            }
            else
            {
                var vo = combomBox.SelectedItem as CompanyVo;
                if (vo == null)
                {
                    msg = "请选择，再点击锁定";
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                lockReceiverCompanyVo = vo;
                //点击锁定
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(btn, lockG);
                btn.Foreground = Brushes.PaleVioletRed;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = new List<CompanyVo>() { lockReceiverCompanyVo };
                combomBox.IsEnabled = false;
                combomBox.SelectedIndex = 0;
            }
        }
        #endregion

        #region lock 物料名称


        private void LockMaterialBtn_Click(object sender, RoutedEventArgs e)
        {
            var combomBox = this.materialCb;
            string title = InfoElement.GetTitle(combomBox);
            var btn = this.lockMaterialBtn;
            string msg;
            if (lockMaterialVo != null)
            {
                //点击解锁
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(btn, unlockG);
                btn.Foreground = Brushes.Gray;
                this.lockMaterialVo = null;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = RuntimeData.Instance.TempMaterial.ToList();
                combomBox.IsEnabled = true;
            }
            else
            {
                var vo = combomBox.SelectedItem as MaterialVo;
                if (vo == null)
                {
                    msg = "请选择，再点击锁定";
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                lockMaterialVo = vo;
                //点击锁定
                btn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(btn, lockG);
                btn.Foreground = Brushes.PaleVioletRed;
                combomBox.ItemsSource = null;
                combomBox.ItemsSource = new List<MaterialVo>() { lockMaterialVo };
                combomBox.IsEnabled = false;
                combomBox.SelectedIndex = 0;
            }
        }

        #endregion

        #endregion
    }
}
